
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:plugin_echat/ec_access_conditions.dart';
import 'package:plugin_echat/ec_message_entity.dart';
typedef UnreadCountChangeListener(int unreadCount);
class QiYuMethodCallHandler {
  QiYuMethodCallHandler();

  List<UnreadCountChangeListener> _unreadCountChangeListeners = [];

  void register(dynamic listener) {
    if (listener is UnreadCountChangeListener) {
      _unreadCountChangeListeners.add(listener);
    }
  }

  void unregister(dynamic listener) {
    if (listener is UnreadCountChangeListener) {
      _unreadCountChangeListeners.removeWhere((v) => v == listener);
    }
  }

  Future<dynamic> handler(MethodCall call) {
    switch (call.method) {
      case 'onUnreadCountChange':
        for (var unreadCountChangeListener in _unreadCountChangeListeners) {
          int unreadCount = call.arguments['unreadCount'];
          unreadCountChangeListener(unreadCount);
        }
        break;
      default:
        throw new UnsupportedError("Unrecognized Method");
    }
    return null!;
  }
}

class Echat {
  /// flutter 调用原生通道
  static const MethodChannel _channel = const MethodChannel('flutter_plugin_echat');
  /// 原生调用，回调处理
  // static EchatMethodCallHandler _methodCallHandler = EchatMethodCallHandler();
  static QiYuMethodCallHandler _methodCallHandler = QiYuMethodCallHandler();
  /// 初始化一洽SDK
  static Future<bool> registerApp({String? appId, String? appSecret}) async {
     _channel.setMethodCallHandler(_methodCallHandler.handler);
    return await _channel.invokeMethod('registerApp', {
      'appId': appId,
      'appSecret': appSecret,
    });
  }

  /// 打开一洽会话窗口
  static Future<bool> openEchatSessionWindow(ECAccessConditions accessConditions) async {
    return await _channel.invokeMethod('openEchatSessionWindow', accessConditions.toJson());
  }

  /// 静态获取未读消息总数
  static Future<int> getUnReadMsgCount() async {
    return await _channel.invokeMethod('getUnReadMsgCount');
  }

  /// 静态获取最后一条消息
  static Future<ECMessageEntity> getLastMessage() async {
    Map<String, dynamic> result = await _channel.invokeMethod('getLastMessage');
    return ECMessageEntity.fromJson(result);
  }

  /// 关闭连接
  static Future<bool> closeCurrentConversation() async {
    return await _channel.invokeMethod('closeCurrentConversation');
  }

  /// 退出登录
  static Future<bool> logout() async {
    return await _channel.invokeMethod('logout');
  }

  /// 清除大文件
  static Future<bool> cleanMemory() async {
    return await _channel.invokeMethod('cleanMemory');
  }

  /// 清除所有文件
  static Future<bool> cleanAllMemory() async {
    return await _channel.invokeMethod('cleanMemory');
  }
}


class EchatMethodCallHandler {
  EchatMethodCallHandler();

  Future<dynamic> handler(MethodCall call) {
    switch (call.method) {
      case 'getUnReadMessage':
        break;
      default:

    }
    return null!;
  }
}
